import { Component } from '@tarojs/taro'
import lodash from "@/utils/lodash"

export default class FyComponent<P = {}, S = {}> extends Component<P, S> {
  state: any
  timer: any
  seconds: any
  prevProps: any

  static options = {
    addGlobalClass: true
  }

  constructor(props) {
    super(...arguments)
    this.timer = undefined
    this.seconds = props.seconds
    this.prevProps = {}
  }

  componentDidMount() {
    this.prevProps = lodash.cloneDeep(this.props)
    this.setTimer(this.prevProps.seconds)
  }

  componentWillReceiveProps(nextProps) {
    // console.log('倒计时：componentWillReceiveProps')
    if (JSON.stringify(this.prevProps) === JSON.stringify(nextProps)) return
    // console.log('倒计时：------------ componentWillReceiveProps ------------')
    this.prevProps = lodash.cloneDeep(nextProps)
    this.clearTimer()
    this.setTimer(nextProps.seconds)
  }

  //  在一个组件被 卸载(unmounted) 和 销毁(destroyed) 之前立即被调用
  componentWillUnmount() {
    this.clearTimer()
  }

  /**
   * 开启倒计时
   */
  setTimer(seconds) {
    this.seconds = seconds
    if (!this.timer) this.countdown()
  }

  /**
   * 清除计时器
   */
  clearTimer() {
    if (this.timer) {
      clearTimeout(this.timer as number)
      this.timer = undefined
    }
  }

  /**
   * 倒计时
   */
  countdown() {
    if (this.seconds === undefined) {
      return;
    }

    //  回调
    // @ts-ignore
    this.onCallBack && this.onCallBack(this.seconds)

    this.seconds--
    if (this.seconds < 0) {
      this.clearTimer()
      // @ts-ignore
      this.onTimeUp && this.onTimeUp()
      return
    }

    this.timer = setTimeout(() => {
      this.countdown()
    }, 1000)
  }

  //  格式化时间数字
  formatNum(num) {
    return (num < 10 ? `0${num}` : `${num}`)
  }
}
